<?php

namespace App\Http\Controllers\Estate;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\ElectricMonitor;

class MonitorController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        $limit = $request->get('limit', 20);
        $res = ElectricMonitor::query()->select('id', 'title', 'url', 'status', 'create_time', 'description')->orderByDesc('id')->paginate($limit);

        return $this->success($res);

    }

    /**
     * Store a newly created resource in storage.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        try {
            $data = $request->post();
            ElectricMonitor::query()->create($data);
        } catch (\Exception $exception) {
            return $this->error('添加失败，标题重复');
        }
        return $this->success();
    }

    /**
     * Display the specified resource.
     *
     * @param int $id
     * @return array
     */
    public function show($id)
    {
        $data = ElectricMonitor::query()->where('id', $id)->first();

        return $this->success($data);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param \Illuminate\Http\Request $request
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        try {
            $data = $request->post();
            ElectricMonitor::query()->where('id', $id)->update($data);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
        return $this->success();
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $ids = explode(',', $id);
        $res = ElectricMonitor::query()->whereIn('id', $ids)->delete();

        return $res ? $this->success() : $this->error();
    }

    public function status(Request $request)
    {
        $id = $request->get('id');
        $state = ElectricMonitor::query()->where('id', $id)->value('status');

        $res = ElectricMonitor::query()->where('id', $id)->update(['status' => $state ? 0 : 1]);

        return $res ? $this->success() : $this->error();
    }
}
